/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the
 * GPL version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin;

import org.digitalsoul.switchplugin.patterns.IPattern;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;


public class PatternRing implements Iterable<IPattern> {

    private int index = 0;
    private final List<IPattern> patternList;
    
    public PatternRing(List<IPattern> patternList) {
        this.patternList = patternList;
    }
    
    public PatternRing() {
        this(new ArrayList<IPattern>());
    }
    
    public void add(IPattern pattern) {
        patternList.add(pattern);
    }
    
    public IPattern next() {
        IPattern pattern = patternList.get(index);
        index++;
        return pattern;
    }
    
    public void remove() {
       patternList.remove(index);
    }
    
    public Iterator<IPattern> iterator() {
        return new PatternIterator(this);
    }
    
    public void spoolAfterPattern(IPattern currentPattern) {
        index = patternList.indexOf(currentPattern);
        if (index + 1 < patternList.size()) {
            index++;
        }
        else {
            index = 0;
        }
    }
    
    public class PatternIterator implements Iterator<IPattern> {

        private Iterator<IPattern> iterator = null;
        
        public PatternIterator(PatternRing ring) {
            ArrayList<IPattern> list = new ArrayList<IPattern>();
            for (int i = ring.index; i < ring.patternList.size(); i++) {
                list.add(ring.patternList.get(i));
            }
            for (int i = 0; i < ring.index; i++) {
                list.add(ring.patternList.get(i));
            }
            iterator = list.iterator();
        }
        
        public boolean hasNext() {
            return iterator.hasNext();
        }

        public IPattern next() {
            return iterator.next();
        }

        public void remove() {
            throw new RuntimeException("not implemented aaargh");
        }
    }

    public Collection<IPattern> patterns() {
        return patternList;
    }
    
    public void clear() {
        patternList.clear();
    }
}
